<template>
  <!-- crossorigin="anonymous" -->
  <video
    id="livePlayer"
    ref="livePlayer"
    :style="{'width': '100%', 'height': '100%'}"
    :muted="muted"
    :controls="true"
    preload="auto"
    playsInline
    autoplay
    crossorigin="*"
    webkit-playsinline
    x-webkit-airplay="true"
    x5-playsinline="true"
    @canplay="onVuePlayerStateChange(false, 'canplay')"
    @play="onVuePlayerStateChange(true, 'play')"
    @pause="onVuePlayerStateChange(false, 'pause')"
    @ended="onVuePlayerStateChange(false, 'ended')"
    @abort="onVuePlayerStateChange(false, 'abort')"
    @error="onVuePlayerStateChange(false, 'error')"
    @timeupdate="onTimeUpdate"
    @loadedmetadata="onVuePlayerStateChange(false,'loadedmetadata')"
    @loadeddata="onVuePlayerStateChange(false,'loadeddata')"
    @playing="onVuePlayerStateChange(true,'playing')"
    @playstate="playstate"
  />
</template>

<script>
import Hls from 'hls.js'
import ObjectUtil from '../../utils/object-util'
import Common from '../../utils/common'
export default {
  name: 'HlsVideo',
  props: {
    url: {
      type: [String],
      default: undefined
    },
    muted: {
      type: [Boolean],
      default: false
    }
  },
  data() {
    return {
      lastTime: null
    }
  },
  mounted() {
    const video = this.$refs.livePlayer
    // video.src = this.url
    const index = this.url.lastIndexOf('.')
    const type = this.url.substring(index)
    const ism3u8 = type.trim(type)

    if (ism3u8 == '.m3u8') {
      this.Init()
    } else {
      video.src = this.url + '?' + Date.now().toString()
    }

    console.log(type, '视频格式')
  },
  beforeDestroy() {
    this.unInit()
  },
  methods: {
    playstate(val) {
      console.log(val)
      if (val) {
        this.play()
      } else {
        this.stop()
      }
    },
    // 更新视频时间。节流，每秒触发一次
    onTimeUpdate() {
      const nowTime = Date.now()
      const gapTime = 1000
      // if (!this.lastTime || nowTime - this.lastTime >= gapTime) {
      if (this.$refs.livePlayer) {
        const time = this.$refs.livePlayer.currentTime
        // this.initVideo.currentTime = time
        this.$emit('updateCurrentTime', time)
      }
      this.lastTime = nowTime
      // }
    },
    onVuePlayerStateChange(playing, name) {
      console.log(playing, name)
      if (name === 'error') {
        this.showErrorToast('播放失败，请重试')
        this.$emit('changeState', false)
      }
      if (name === 'loadedmetadata') {
        this.$emit('loadedmetadata', this.$refs.livePlayer.duration)
      }
      if (name === 'canplay') {
        this.$emit('changeState', true)
        // this.play()
      }
      if (name === 'ended') {
        this.$emit('changeState', false)
      }
      this.$emit('event', { playing: playing, name: name })
    },
    stop() {
      this.$refs.livePlayer.pause()
    },
    unInit() {
      console.log('unInit', this.hls)
      if (ObjectUtil.notNull(this.hls)) {
        this.$refs.livePlayer.pause()
        this.hls.destroy()
        this.hls = null
      }
    },
    Init() {
      console.log(this.url, 'url')
      const that = this
      if (Hls.isSupported()) {
        that.hls = new Hls()
        that.hls.loadSource(that.url)
        that.hls.attachMedia(that.$refs.livePlayer)
        that.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          console.log('加载成功')

          that.$refs.livePlayer.play()
        })
        that.hls.on(Hls.Events.ERROR, (event, data) => {
          console.log(event, data)
          // 监听出错事件
          console.log('加载失败', event, data)
        })
      }
    },
    play() {
      this.$refs.livePlayer.play()
    },
    currentTime(time) {
      const that = this
      if (ObjectUtil.notNull(that.$refs.livePlayer)) {
        if (ObjectUtil.notNull(time)) {
          that.$refs.livePlayer.currentTime = time
        } else {
          return that.$refs.livePlayer.currentTime
        }
      }
    },
    clipImage() {
      const canvas = document.createElement('canvas')
      const canvasCtx = canvas.getContext('2d')
      const video = document.getElementById('livePlayer')
      const rW = video.videoWidth
      const rH = video.videoHeight
      let tW, tH
      const target = 720
      if (rW > rH) {
        tW = target
        tH = Common.video2Equalratio(rW, rH, target)
      } else {
        tW = Common.video2Equalratio(rW, rH, target)
        tH = target
      }
      // video.useCORS=true;//解决跨域
	    // video.crossOrigin="Anonymous";// 这两个参数必填 解决跨域
      canvas.width = tW
      canvas.height = tH
      canvasCtx.drawImage(video, 0, 0, tW, tH)
      const dataUrl = canvas.toDataURL('image/png')
      return dataUrl
    }
  }
}
</script>

<style scoped>
  #livePlayer{
    border-radius: 15px;
  }
</style>
